package zjh.filter;


import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

public class LoginFilter extends ZuulFilter {

    //filter类型
    @Override
    public String filterType() {
        return "pre";
    }

    //执行顺序
    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //获取请求地址
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        //判断当前地址后缀是否是以下格式结尾
        if (requestURI.endsWith("login")||requestURI.endsWith("register")){
            return false;
        }
        return true;
    }


    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        //获取请求地址
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();

        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();

        response.setContentType("application/json;charset=utf-8");

        String token = request.getHeader("token");

        if (!StringUtils.hasLength(token)){
            PrintWriter writer = response.getWriter();

            HashMap<String, Object> map = new HashMap<>();
            map.put("success", false);
            map.put("message", "登录校验失败，请重新登录！");

            String s = JSON.toJSONString(map);
            writer.write(s);
            // 2.阻止后续filter执行
            RequestContext.getCurrentContext().setSendZuulResponse(false);

        }
        // 如果要放行，这里返回null即可，不用管
        return null;
    }
}
